<?php defined("MAIN_DIR") or die("No direct access");

$error = array();
if (isset($_GET['act']) && $_GET['act'] == "search")
{
	if (isset($_GET['type']) && $_GET['type'] != "")
	{
		$type = trim(strip_tags($_GET['type']));
		$type_name = "";
		$type_number = 0;
		switch ($type)
		{
			case "needs": $type_name = "credit"; $type_number = 1; break;
			case "auto": $type_name = "auto"; $type_number = 2; break;
			case "home": $type_name = "home"; $type_number = 3; break;
			case "carts": $type_name = "cart"; $type_number = 4; break;
			case "business": $type_name = "business"; $type_number = 5; break;
			default: $error['type'] = 1;
		}
		if (!isset($error['type']))
			$credit_query = 
				"select `B`.`link`,`B`.`name` as `bank_name`,`CC`.*,`C`.`name` as `credit_name`,`city`.`path`
				from `bank` as `B`
					left join `city`
						on `city`.`city_id` = `B`.`city_id`
				,`credit_currency` as `CC`,`$type_name` as `C`
				where
					`C`.`bank_id` = `B`.`bank_id` and `C`.`{$type_name}_id` = `CC`.`credit_id` and `CC`.`type` = '$type_number' and 
					(
						(`C`.`regionally` = '1' and
							(
								`B`.`bank_id` in (select `parent` from `bank` where `city_id` = '$_SESSION[city]' and `parent` != '0' ) or
								`B`.`bank_id` in (select `bank_id` from `bank` where `city_id` = '$_SESSION[city]' and `parent` = '0' )
							)
						) or
						(`B`.`city_id` = '$_SESSION[city]' and `C`.`regionally` = '0')
					)";
	}
	else
		$error['type'] = 1;
	
	if (isset($_GET['currency']) && $_GET['currency'] != "" && count($error) == 0)
	{
		$cur = trim(strip_tags($_GET['currency']));
		switch ($cur)
		{
			case "rub": $credit_query .= " and `CC`.`currency` = 'RUB'"; break;
			case "usd": $credit_query .= " and `CC`.`currency` = 'USD'"; break;
			case "euro": $credit_query .= " and `CC`.`currency` = 'EUR'"; break;
			default: $error['currency'] = 1;
		}
	}
	else
		$error['currency'] = 1;
	
	if (isset($_GET['sum']) && $_GET['sum'] != "" && count($error) == 0)
	{
		$sum = trim(strip_tags($_GET['sum']));
		if (is_numeric($sum))
			$credit_query .= " and `CC`.`sum_low` <= '$sum' and `CC`.`sum_high` >= '$sum'";
	}
	
	if (isset($_GET['period']) && $_GET['period'] != "" && count($error) == 0)
	{
		$period = explode("-",trim(strip_tags($_GET['period'])));
		if (count($period) == 2)
			$credit_query .= " and ('".$period[0]."' between `CC`.`period_low` and `CC`.`period_high` or '".$period[1]."' between `CC`.`period_low` and `CC`.`period_high`)";
		elseif (count($period) == 1)
			$credit_query .= " and (`CC`.`period_low` >= '".$period[0]."' or `CC`.`period_high` >= '".$period[0]."')";
	}
	
	if (isset($_GET['sort']) && $_GET['sort'] != "" && isset($_GET['ord']) && $_GET['ord'] != "" && count($error) == 0)
	{
		$sort = trim(strip_tags($_GET['sort']));
		$ord = trim(strip_tags($_GET['ord']));
		switch($sort)
		{
			case "period": $credit_query .= ($ord == "desc") ? " order by `period_high` desc" : " order by `period_low` asc"; break;
			case "sum": $credit_query .= ($ord == "desc") ? " order by `sum_high` desc" : " order by `sum_low` asc"; break;
			case "rate": $credit_query .= ($ord == "desc") ? " order by `rate_high` desc" : " order by `rate_low` asc"; break;
			default: $credit_query .= " order by `period_low` asc";
		}
	}
	
	if (count($error) == 0)
	{
		$limit = 20;
		$credit_result = mysql_query($credit_query);
		$count = mysql_num_rows($credit_result);
		$page = 1;
		if (isset($_GET['page']))
			$page = $_GET['page'];
		$max_page = ceil($count/$limit);
		if ($max_page == 0)
			$max_page++;
		if ($page > $max_page)
			$page = $max_page;
		elseif ($page < 1)
			$page = 1;
		$start_list = (ceil($page)-1)*$limit;
		$credit_query .= " limit $start_list,$limit";
		$credit_result = mysql_query($credit_query);
		$credit_count = mysql_num_rows($credit_result);
	}
}

$head_title = "Кредиты в ".$current_city['city_name_pred'];
$head_description = "Поиск по кредитам в банках ".$current_city['city_name_rod'];
$head_keywords = "кредит ".$current_city['city_name'];

if (isset($_GET['type']) && $_GET['type'] != "")
{
	$type = trim(strip_tags($_GET['type']));
	switch ($type)
	{
		case "needs": 	$head_title = "Потребительские кредиты в ".$current_city['city_name_pred'];
						$head_description = "Поиск по потребительским кредитам в банках ".$current_city['city_name_rod'];
						$head_keywords = "потребительские кредиты ".$current_city['city_name'];
						break;
		case "auto":	$head_title = "Кредиты на покупку авто, автокредиты в ".$current_city['city_name_pred'];
						$head_description = "Поиск по автокредитам в банках ".$current_city['city_name_rod'];
						$head_keywords = "автокредит кредит на авто ".$current_city['city_name'];
						break;
		case "home": 	$head_title = "Ипотека в ".$current_city['city_name_pred'];
						$head_description = "Поиск по ипотечным кредитам в банках ".$current_city['city_name_rod'];
						$head_keywords = "ипотека ".$current_city['city_name'];
						break;
		case "carts": 	$head_title = "Кредитные банковские карты в ".$current_city['city_name_pred'];
						$head_description = "Поиск по кредитным картам в банках ".$current_city['city_name_rod'];
						$head_keywords = "кредитная банковская карта ".$current_city['city_name'];
						break;
		case "business":$head_title = "Кредиты бизнесу в ".$current_city['city_name_pred'];
						$head_description = "Поиск по кредитам для бизнеса в банках ".$current_city['city_name_rod'];
						$head_keywords = "кредиты бизнес ".$current_city['city_name'];
						break;
	}
}

require_once APP.HEADFILE;
?>
<script type="text/javascript" src="/files/js/bank_list.js"></script>
<script type="text/javascript">
var per = 0;
<?php if (isset($_GET['period'])) echo "per='$_GET[period]';\n"; ?>
$(document).ready(function(){
	$("#type").change(function(){
		if ($(this).val() != 0)
			$("#errors > #type_er").remove();
		request = $.parseJSON(getPeriod($(this).val()));
		$("#period").empty();
		for (var i = 0; i < request.find.length; i++)
		{
			var str = "<option value='"+request.find[i].value+"'>"+request.find[i].name+"</option>";
			$("#period").append(str);
		}
	})
	$("#currency").change(function(){
		if ($(this).val() != 0)
			$("#errors > #currency_er").remove();
	})
	
	$("#type").change();
	$("#period option[value='"+per+"']").attr("selected","selected");
})
function check_form()
{
	var value = true;
	$("#errors").html("");
	if ($("#type").val() == 0)
	{
		$("#errors").append("<span id='type_er'>Необходимо выбрать тип кредита<br /></span>");
		value = false;
	}
	if ($("#currency").val() == 0)
	{
		$("#errors").append("<span id='currency_er'>Необходимо выбрать валюту<br /></span>");
		value = false;
	}
	
	return value;
}
function getPeriod(type)
{
	switch(type)
	{
		case "home": return '{"find":[{"name":"1 год","value":"0-12"},{"name":"2 года","value":"12-24"},{"name":"3 года","value":"24-36"},{"name":"4 года","value":"36-48"},{"name":"5 лет","value":"48-60"},{"name":"10 лет","value":"60-120"},{"name":"15 лет","value":"120-180"},{"name":"20 лет","value":"180-240"},{"name":"25 лет","value":"240-300"},{"name":"30 лет","value":"300-360"}]}';
					break;
		case "needs": return '{"find":[{"name":"3 месяца","value":"0-3"},{"name":"6 месяцев","value":"3-6"},{"name":"1 год","value":"6-12"},{"name":"2 года","value":"12-24"},{"name":"3 года","value":"24-36"},{"name":"5 лет и более","value":"36"}]}';
					break;
		case "auto": return '{"find":[{"name":"6 месяцев","value":"0-6"},{"name":"1 год","value":"6-12"},{"name":"2 года","value":"12-24"},{"name":"3 года","value":"24-36"},{"name":"5 лет и более","value":"36"}]}';
					break;
		case "carts": return '{"find":[{"name":"3 месяца","value":"0-3"},{"name":"6 месяцев","value":"3-6"},{"name":"1 год","value":"6-12"},{"name":"2 года","value":"12-24"},{"name":"3 года","value":"24-36"},{"name":"5 лет и более","value":"36"}]}';
					break;
		case "business": return '{"find":[{"name":"1 год","value":"0-12"},{"name":"2 года","value":"12-24"},{"name":"3 года","value":"24-36"},{"name":"5 лет","value":"36-60"},{"name":"5 лет и более","value":"60"}]}';
					break;
	}
}
</script>
<h1>Кредиты в <?php echo $current_city['city_name_pred']; ?></h1>
<div class="credity_1col">
	<form method="GET" onsubmit="return check_form()">
	<input type='hidden' name='act' value='search' />
	<table width="301" border="0" cellspacing="0" cellpadding="0">
		<tr>
			<td width="39%" align="left" class="golosovanie_form">Город</td>
			<td width="61%" align="left" class="golosovanie_form"><strong><?php echo $current_city['city_name']; ?></strong></td>
		</tr>
		<tr>
			<td align="left" class="golosovanie_form">Тип кредита</td>
			<td align="left" class="golosovanie_form">
				<select name="type" id="type" class="golosovanie_forma">
					<option value="home"<?php
					if (isset($_GET['type']) && $_GET['type'] == "home")
						echo " selected";
					?>>Ипотека</option>
					<option value="needs"<?php
					if (isset($_GET['type']) && $_GET['type'] == "needs")
						echo " selected";
					?>>На срочные нужды</option>
					<option value="auto"<?php
					if (isset($_GET['type']) && $_GET['type'] == "auto")
						echo " selected";
					?>>На авто</option>
					<option value="carts"<?php
					if (isset($_GET['type']) && $_GET['type'] == "carts")
						echo " selected";
					?>>Кредитные карты</option>
					<option value="business"<?php
					if (isset($_GET['type']) && $_GET['type'] == "business")
						echo " selected";
					?>>Бизнесу</option>
				</select>
			</td>
		</tr>
		<tr>
			<td align="left" class="golosovanie_form">Валюта</td>
			<td align="left" class="golosovanie_form">
				<select name="currency" id="currency" class="golosovanie_forma">
					<option value="rub"<?php
					if (isset($_GET['currency']) && $_GET['currency'] == "rub")
						echo " selected";
					?>>Рубли</option>
					<option value="usd"<?php
					if (isset($_GET['currency']) && $_GET['currency'] == "usd")
						echo " selected";
					?>>Доллары</option>
					<option value="euro"<?php
					if (isset($_GET['currency']) && $_GET['currency'] == "euro")
						echo " selected";
					?>>Евро</option>
				</select>
			</td>
		</tr>
		<tr>
			<td align="left" class="golosovanie_form">Сумма</td>
			<td align="left" class="golosovanie_form">
				<input name="sum" type="text" class="golosovanie_forma_text" <?php
				if (isset($_GET['sum']))
					echo " value='$_GET[sum]'";
				?>/>
			</td>
		</tr>
		<tr>
			<td align="left" class="golosovanie_form">Срок</td>
			<td align="left" class="golosovanie_form">
				<label for="textfield"></label>
				<select name="period" id="period" class="golosovanie_forma"></select>
			</td>
		</tr>
		<tr>
			<td colspan="2" align="left" class="golosovanie_form"><div class="golosovanie_line"></div></td>
		</tr>
		<tr>
			<td align="left">&nbsp;</td>
			<td align="right" valign="top">
				<input type="submit" class="golosovanie_forma" id="button" value="Найти" />
			</td>
		</tr>
	</table>
	</form>
	<p id="errors" style="color:red"><?php
	if (count($error) > 0)
	{
		if (isset($error['type']))
			echo "<span id='type_er'>Необходимо выбрать тип кредита<br /></span>";
		if (isset($error['currency']))
			echo "<span id='currency_er'>Необходимо выбрать валюту<br /></span>";
	}
	?></p>
</div><?php
if (!isset($_GET['act']))
{
	$min_query = "select `CC`.`cc_id`,`CC`.`credit_id`,`CC`.`type`,`CC`.`rate_low`,`CC`.`rate_high`,`C`.`name` as `c_name`,`H`.`name` as `h_name`,`A`.`name` as `a_name`,`Cr`.`name` as `cr_name`,`Bs`.`name` as `bs_name`, `B`.`link`, `B`.`name`
	from `credit_currency` as `CC`,`credit` as `C`,`home` as `H`,`auto` as `A`,`cart` as `Cr`,`business` as `Bs`,`bank` as `B`,`city` as `Ct`
	where `CC`.`currency` = 'RUB' and (
		(`CC`.`credit_id` = `C`.`credit_id` and `CC`.`type` = '1' and `C`.`bank_id` = `B`.`bank_id`) or
		(`CC`.`credit_id` = `A`.`auto_id` and `CC`.`type` = '2' and `A`.`bank_id` = `B`.`bank_id`) or
		(`CC`.`credit_id` = `H`.`home_id` and `CC`.`type` = '3' and `H`.`bank_id` = `B`.`bank_id`) or
		(`CC`.`credit_id` = `Cr`.`cart_id` and `CC`.`type` = '4' and `Cr`.`bank_id` = `B`.`bank_id`) or
		(`CC`.`credit_id` = `Bs`.`business_id` and `CC`.`type` = '5' and `Bs`.`bank_id` = `B`.`bank_id`)
	) and `Ct`.`city_id` = `B`.`city_id` and (
		(`B`.`city_id` = '$_SESSION[city]' and `B`.`parent` <> '0') or
		(`B`.`parent` = '0')
	)
	group by `CC`.`cc_id`
	order by `CC`.`rate_low`,`CC`.`rate_high` limit 4";
	$min_res = mysql_query($min_query) or die(mysql_error());
	if (mysql_num_rows($min_res) > 0)
	{
		?><div class="credity_2col" id="credity_min">
			<strong>Mинимальные ставки</strong><?php
		while ($min_row = mysql_fetch_array($min_res))
		{
			switch ($min_row['type'])
			{
				case "1": 	$cr_name = "c_name";
							$type = "На срочные нужды";
							$link = "needs";
							$c_link = "/$c_name/credits/credit/";
							break;
				case "2": 	$cr_name = "a_name";
							$type = "На покупку авто";
							$link = "auto";
							$c_link = "/$c_name/credits/auto/";
							break;
				case "3": 	$cr_name = "h_name";
							$type = "Ипотека";
							$link = "home";
							$c_link = "/$c_name/credits/home/";
							break;
				case "4": 	$cr_name = "cr_name";
							$type = "Кредитные карты";
							$link = "carts";
							$c_link = "/$c_name/credits/cart/";
							break;
				case "5": 	$cr_name = "bs_name";
							$type = "Бизнесу";
							$link = "business";
							$c_link = "/$c_name/credits/business/";
							break;
			}
			?>
				<div class="credity_min_heading">
					<a href="<?php echo "?type=$link"?>" class="credity_blue_link"><strong><?php echo $type; ?></strong></a>
					в банке «<a href="<?php echo "/$c_name";?>/banks/<?php echo $min_row['link'].".html"; ?>" class="credity_green_link"><strong><?php echo $min_row['name']; ?></strong></a>»
				</div>
				<div><a href="<?php echo $c_link.$min_row['credit_id']; ?>" class="credity_blue_link"><?php echo $min_row[$cr_name]; ?></a></div>
				<div class="credity_min_percent"><?php echo "от $min_row[rate_low] до $min_row[rate_high] %"?></div>
			<?php
		}
		?></div><?php
	}
}
?><div style="clear:both"></div><?php
if (isset($_GET['act']) && $_GET['act'] == "search" && count($error) == 0)
{
	$url = parse_url($_SERVER['REQUEST_URI']);
	if (isset($url['query']))
		$url_q = explode("&",$url['query']);
	
	$tmp = array();
	for ($z=0; $z<count($url_q); $z++)
		if ((strpos($url_q[$z],"sort=") === false) && (strpos($url_q[$z],"ord=") === false) && ($url_q[$z] != ""))
			$tmp[] = $url_q[$z];
	$link = "?".implode("&",$tmp)."&sort=";
	?><div id="kredity_result">
		<div class="kredity_result_heading">Результаты поиска</div><?php
		if ($count > 0)
		{
			?><table width="100%" border="0" cellspacing="0" cellpadding="8">
				<tr>
					<td width="19%" align="left" bgcolor="#FFFFFF"><strong>Банк</strong></td>
					<td width="38%" align="left" bgcolor="#FFFFFF"><strong>Название</strong></td>
					<td width="17%" align="left" bgcolor="#FFFFFF"><strong>Срок</strong></td>
					<td width="17%" align="left" bgcolor="#FFFFFF"><strong>Сумма</strong>, <?php
					switch($cur)
					{
						case "rub": echo "руб."; break;
						case "usd": echo "$"; break;
						case "euro": echo "евро"; break;
					}
					?></td>
					<td width="10%" align="left" bgcolor="#FFFFFF"><strong>Ставка</strong>, %</td>
				</tr>
				<tr>
					<td align="left">&nbsp;</td>
					<td align="left">&nbsp;</td>
					<td align="left">
						<a href="<?php echo $link."period&ord=asc";?>"><img src="/files/images/arr_table_top.png" width="7" height="7" border="0" /></a>
						<a href="<?php echo $link."period&ord=desc";?>"><img src="/files/images/arr_table_bottom.png" alt="" border="0" /></a>
					</td>
					<td align="left">
						<a href="<?php echo $link."sum&ord=asc";?>"><img src="/files/images/arr_table_top.png" alt="" width="7" height="7" border="0" /></a>
						<a href="<?php echo $link."sum&ord=desc";?>"><img src="/files/images/arr_table_bottom.png" alt="" border="0" /></a>
					</td>
					<td align="left">
						<a href="<?php echo $link."rate&ord=asc";?>"><img src="/files/images/arr_table_top.png" alt="" width="7" height="7" border="0" /></a>
						<a href="<?php echo $link."rate&ord=desc";?>"><img src="/files/images/arr_table_bottom.png" alt="" border="0" /></a>
					</td>
				</tr><?php
				while ($credit_row = mysql_fetch_array($credit_result))
				{
					switch ($type) {
						
						case "needs": $cr_link = "/".$credit_row['path']."/credits/credit/".$credit_row['credit_id']; break;
						case "auto": $cr_link = "/".$credit_row['path']."/credits/auto/".$credit_row['credit_id']; break;
						case "home": $cr_link = "/".$credit_row['path']."/credits/home/".$credit_row['credit_id']; break;
						case "carts": $cr_link = "/".$credit_row['path']."/credits/cart/".$credit_row['credit_id']; break;
						case "business": $cr_link = "/".$credit_row['path']."/credits/business/".$credit_row['credit_id']; break;
					}
					?><tr>
						<td align="left"><a href="<?php echo "/".$c_name;?>/banks/<?php echo $credit_row['link'].".html"; ?>" class="credity_green_link"><?php
							echo $credit_row['bank_name']; ?></a></td>
						<td align="left"><a href="<?php echo $cr_link; ?>" class="credity_blue_link"><?php
							echo $credit_row['credit_name'];?></a></td>
						<td align="left"><?php
							echo getPeriod($credit_row['period_low'],false)." - ".getPeriod($credit_row['period_high']);
						?></td>
						<td align="left"><?php
							echo "от ".getValue($credit_row['sum_low'])." до ".getValue($credit_row['sum_high']);
						?></td>
						<td align="left"><?php
							echo $credit_row['rate_low']."-".$credit_row['rate_high'];
						?></td>
					</tr><?php
				}
			?></table><?php
			require_once APP."pageskin.php";
		} else {
			echo "<span class='gag'>Не найдено подходящего кредита</span>";
		}
    ?></div><?php
}
?><div class="inside_block">
	<table width="100%" border="0" cellpadding="0" cellspacing="0">
		<tr valign='top'>
			<td width="344" class="inside_info"><?php
				require_once APP."bank_list.php";
				require_once APP."currency_rates.php";
			?></td>
			<td width="646"><?php
				$info = mysql_fetch_array(mysql_query("select * from `info` where `info_id` = '10' limit 1"));
				$text = getRichText($info['text']);
				echo "<h2>$info[header]</h2>";
				echo "<p>$text</p>";
			?></td>
		</tr>
	</table>
</div>
<?php require_once APP.FOOTERFILE; ?>